<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['仓库管理', '库存调拨']"
      marginBottom="10px"
      currentMenu="新建调拨单"
    ></crumbs>
    <div class="form-body">
      <div class="cards-box">
        <a-card title="基本信息" :bordered="false" style="margin-top: 12px">
          <a-form-model ref="ruleFormTwo" :model="buildForm" :rules="rules">
            <a-row>
              <a-col :span="7">
                <a-form-model-item label="调拨单号" style="width: 100%" prop="orderNumber">
                  <a-input
                    v-model="buildForm.orderNumber"
                    placeholder="请输入"
                    @blur="checkInputValue(buildForm.orderNumber)"
                  />
                  <span class="btn-text code-btn" @click="genEntityCode">自动生成</span>
                </a-form-model-item>
              </a-col>
              <a-col :span="1"></a-col>
              <a-col :span="7">
                <a-form-model-item label="调拨日期" style="width: 100%" prop="operateTime">
                  <a-date-picker v-model="buildForm.operateTime" style="width: 100%" @change="operaChange" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="7">
                <a-form-model-item label="调出仓库" style="width: 100%" prop="warehouseOutId">
                  <a-select
                    show-search
                    v-model="buildForm.warehouseOutId"
                    class="row-input"
                    @change="stockOutChange"
                    allowClear
                    placeholder="请选择"
                    :filter-option="filterOption"
                  >
                    <a-select-option :value="item.id" v-for="item in stockLIst" :key="item.id">
                      {{ item.warehouseName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="1"></a-col>
              <a-col :span="7">
                <a-form-model-item label="调入仓库" style="width: 100%" prop="warehouseInId">
                  <a-select
                    show-search
                    v-model="buildForm.warehouseInId"
                    class="row-input"
                    @change="stockInChange"
                    allowClear
                    placeholder="请选择"
                    :filter-option="filterOption"
                  >
                    <a-select-option :value="item.id" v-for="item in stockLIst" :key="item.id">
                      {{ item.warehouseName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="1"></a-col>
              <a-col :span="7">
                <a-form-model-item label="调拨明细记录方式" style="width: 100%" prop="warehouseId">
                  <a-select
                    show-search
                    v-model="buildForm.type"
                    class="row-input"
                    @change="stockTypeChange"
                    allowClear
                    placeholder="请选择"
                    :filter-option="filterOption"
                  >
                    <a-select-option :value="item.value" v-for="item in stockTypeList" :key="item.value">
                      {{ item.text }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="23">
                <a-form-model-item label="调拨原因" style="width: 100%">
                  <a-textarea v-model="buildForm.remark" :maxLength="500" placeholder="请输入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="23">
                <a-form-model-item label="附件" style="flex: 1">
                  <file-upload :ids="buildForm.dingFileInfo" @getFileList="getFileList"></file-upload>
                  <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，大小不可超过20M</p>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
        <a-card title="调拨明细" :bordered="false" style="margin-top: 12px">
          <j-editable-table
            ref="goodsTable"
            :loading="goodsTable.loading"
            :columns="goodsTable.columns"
            :dataSource="goodsTable.dataSource"
            :maxHeight="300"
            :actionButton="true"
            @added="tableAddRow"
            :addActionButton="false"
          >
            <template #options>
              <a-button type="primary" icon="plus" @click="selectMulti">新增</a-button>
            </template>
            <template v-slot:goodsCode="props">
              <div style="padding-left: 10px">
                <a-input
                  placeholder="请选择"
                  :read-only="true"
                  @click="showSelect(props)"
                  :value="projectNameText(props)"
                  :class="projectNameText(props) ? 'has-value' : ''"
                >
                  <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                  <a-icon
                    slot="suffix"
                    type="close-circle"
                    theme="filled"
                    class="close-icon"
                    @click="getSelectValue(false, '', [], props)"
                  />
                </a-input>
              </div>
              <goodsTableSelect
                ref="goodsTableSelect"
                @getSelectValue="(id, text, item) => getSelectValue(id, text, item, props)"
                :key="selectIndex"
              >
              </goodsTableSelect>
            </template>
            <template v-slot:goodsName="props">
              <a-input v-model="props.text" disable></a-input>
            </template>
            <template v-slot:goodsQualifiedNum="props">
              <!-- <a-input
                v-model="props.text"
                placeholder="请输入"
                :suffix="checkUnit(props)"
                @input="(e) => inputNum(e, props, 'goodsQualifiedNum')"
              ></a-input> -->
              <a-input
                v-model="props.text"
                @input="(e) => inputNum(e, props, 'goodsQualifiedNum')"
                placeholder="请输入"
              >
                <div
                  slot="addonAfter"
                  style="width: 80px; overflow: hidden; white-space: nowrap; text-overflow: ellips"
                >
                  <a-select
                    :default-value="dataSourceItem(props, 'selectUnitQ')"
                    @change="(e) => qualifiedChange(e, props)"
                    style="width: 80px"
                  >
                    <a-select-option v-for="unit in dataSourceItem(props, 'unitList')" :value="unit.id" :key="unit.id">
                      {{ unit.unit }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-input>
            </template>
            <template v-slot:goodsScrapNum="props">
              <!-- <a-input
                v-model="props.text"
                placeholder="请输入"
                :suffix="checkUnit(props)"
                @input="(e) => inputNum(e, props, 'goodsScrapNum')"
              ></a-input> -->
              <a-input v-model="props.text" @input="(e) => inputNum(e, props, 'goodsScrapNum')" placeholder="请输入">
                <div
                  slot="addonAfter"
                  style="width: 80px; overflow: hidden; white-space: nowrap; text-overflow: ellips"
                >
                  <a-select
                    :default-value="dataSourceItem(props, 'selectUnitS')"
                    @change="(e) => scrapNumChange(e, props)"
                    style="width: 80px"
                  >
                    <a-select-option v-for="unit in dataSourceItem(props, 'unitList')" :value="unit.id" :key="unit.id">
                      {{ unit.unit }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-input>
            </template>
            <template v-slot:action="props">
              <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteGood(props)">
                <span class="del-text">删除</span>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-card>
        <div>
          <Examine
            @submitProcess="submitProcess"
            :type="jkeForm.title === '新建调拨单' ? '0' : '1'"
            id="WMS_STOCK_ALLOT"
            ref="examine"
          />
          <div style="height: 50px"></div>
        </div>
      </div>
    </div>
    <goodsTableSelect ref="goodsTableSelectMulti" @getSelectValue="getSelectMultiValue" :key="selectMultiIndex">
    </goodsTableSelect>
    <div class="footer-submit form-footer">
      <a-button type="primary" @click="submitProcess" :loading="submitLoading"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import moment from 'moment'
import { clearNoNum, numFormat, validateDuplicateValue, accAdd, accMul, accDivMin } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import goodsTableSelect from '@/components/goodsTableSelect'
import Examine from '@/components/examine'
import {
  stockListApi,
  queryGoodApi,
  batchStockApi,
  stockAllocQueryWarehouse,
  stockAllocQueryWarehouseGoods,
  stockAllocationAddApi,
  checkGoodsExceedApi,
} from '@/api/erpApi'
export default {
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    goodsTableSelect,
    Examine,
  },
  data() {
    return {
      jkeForm: {
        title: '新建调拨单',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      numFormat,
      stockGoodList: [],
      peopleList: [],
      stockLIst: [],
      selectIndex: 0,
      selectColumns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsCode',
          searchKey: 'goodsCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '物品名称',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsName',
          searchKey: 'goodsName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          dataIndex: 'spec',
          searchKey: 'spec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'spec',
          },
        },
        {
          title: '物品类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'typeText',
          searchKey: 'type',
          type: 'select',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'typeText',
          },
        },
        {
          title: '物品分类',
          width: 100,
          ellipsis: true,
          dataIndex: 'categoryText',
          searchKey: 'category',
          type: 'tree',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'categoryText',
          },
        },
      ],
      filterForm: {},
      stockTypeList: [
        {
          text: '调拨单生效后，自动生成出库记录、入库记录',
          value: 'automatic_generation',
        },
        {
          text: '调拨后在出入库查询中手动新建出库单、入库单',
          value: 'manual_generation',
        },
      ],
      buildForm: {
        orderNumber: '',
        complete: false,
        dingFileInfo: '',
        operateType: '2',
        operateTaskType: 'O6',
        warehouseOutId: '', //调拨出库
        warehouseInId: '', //调拨入库
        type: 'automatic_generation',
      },
      submitLoading: false, // 提交loading
      rules: {
        orderNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateTime: [{ required: true, message: '请选择', trigger: 'change' }],
        warehouseOutId: [{ required: true, message: '请选择', trigger: 'change' }],
        warehouseInId: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: 'unitList',
            key: 'unitList',
            type: FormTypes.hidden,
          },
          {
            title: 'rateQ',
            key: 'rateQ',
            type: FormTypes.hidden,
          },
          {
            title: 'rateS',
            key: 'rateS',
            type: FormTypes.hidden,
          },
          {
            title: 'rateQOld',
            key: 'rateQOld',
            type: FormTypes.hidden,
          },
          {
            title: 'rateSOld',
            key: 'rateSOld',
            type: FormTypes.hidden,
          },
          {
            title: 'selectUnitQ',
            key: 'selectUnitQ',
            type: FormTypes.hidden,
          },
          {
            title: 'selectUnitS',
            key: 'selectUnitS',
            type: FormTypes.hidden,
          },
          {
            title: 'assistUnit',
            width: '20%',
            key: 'assistUnit',
            type: FormTypes.hidden,
          },
          {
            title: 'kcGoodsQualifiedNum',
            width: '20%',
            key: 'kcGoodsQualifiedNum',
            type: FormTypes.hidden,
          },
          {
            title: 'kcGoodsScrapNum',
            width: '20%',
            key: 'kcGoodsScrapNum',
            type: FormTypes.hidden,
          },
          {
            title: 'goodsId',
            width: '20%',
            key: 'goodsId',
            type: FormTypes.hidden,
          },
          {
            title: '物品编号',
            width: '20%',
            key: 'goodsCode',
            type: FormTypes.slot,
            placeholder: '请选择${title}',
            slotName: 'goodsCode',
            isrequired: true,
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空', // 提示的文本
              },
            ],
          },
          {
            title: '物品名称',
            width: '20%',
            key: 'goodsName',
            type: FormTypes.input,
            placeholder: '',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '规格',
            width: '15%',
            key: 'spec',
            type: FormTypes.input,
            placeholder: '',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '调拨合格品数',
            width: '20%',
            key: 'goodsQualifiedNum',
            type: FormTypes.slot,
            isrequired: true,
            placeholder: '请输入${title}',
            slotName: 'goodsQualifiedNum',
            defaultValue: '0',
            // validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '调拨报废品数',
            width: '20%',
            key: 'goodsScrapNum',
            type: FormTypes.slot,
            isrequired: true,
            placeholder: '请输入${title}',
            slotName: 'goodsScrapNum',
            defaultValue: '0',
            // validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '',
            width: '10%',
            key: 'action',
            type: FormTypes.slot,
            slotName: 'action',
          },
        ],
      },
      formatParams: {},
      processDataVo: {},
      getSelWarehouseGoodsObj: {},
      getSelWarehouseGoodsId: '',
      goodsProps: {},
      selectMultiIndex: 0.1, // 商品多选组件key
      selectdGoodsIds: '', // 商品多选组件-选中值
      selectedGoodsNames: '', // 商品多选组件-选中值的名称
    }
  },
  methods: {
    initForm() {
      this.jkeForm.visible = true
      let user = localStorage.getItem('pro__Login_Userinfo')
      let peopleObj = {
        name: JSON.parse(user).value.realname,
        id: JSON.parse(user).value.id,
      }
      this.peopleList = [peopleObj]
      this.buildForm.operateUserName = JSON.parse(user).value.realname
      this.buildForm.operateUserId = JSON.parse(user).value.id
      let nowDate = new Date()
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1
      let day = nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate()
      let hour = nowDate.getHours()
      let minute = nowDate.getMinutes()
      let second = nowDate.getSeconds()
      let currentTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      // this.buildForm.operateTime = moment(currentTime, 'YYYY-MM-DD hh:mm:ss')
      this.buildForm.operateTime = currentTime
      console.log(currentTime, '---currentTime')
      this.getInStockList()
    },
    // 选择合格品单位
    qualifiedChange(e, props) {
      let { unitList, rateQOld, goodsQualifiedNum } = this.$refs.goodsTable.getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      let old_num = goodsQualifiedNum
        ? accMul(goodsQualifiedNum, rateQOld)
        : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      this.$refs.goodsTable.setValues([
        {
          rowKey: props.rowId,
          values: {
            rateQ: unit.conversionRate,
            rateQOld: unit.conversionRate,
            selectUnitQ: e,
            goodsQualifiedNum: goodsQualifiedNum
              ? accDivMin(old_num, unit.conversionRate)
              : '0' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */,
          },
        },
      ])
      let obj = {
        target: { value: goodsQualifiedNum ? accDivMin(old_num, unit.conversionRate) : '0' },
      }
      this.inputNum(obj, props, 'goodsQualifiedNum')
    },
    // 选择报废品单位
    scrapNumChange(e, props) {
      let { unitList, rateSOld, goodsScrapNum } = this.$refs.goodsTable.getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      let old_num = goodsScrapNum
        ? accMul(goodsScrapNum, rateSOld)
        : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      this.$refs.goodsTable.setValues([
        {
          rowKey: props.rowId,
          values: {
            rateS: unit.conversionRate,
            rateSOld: unit.conversionRate,
            selectUnitS: e,
            goodsScrapNum: goodsScrapNum
              ? accDivMin(old_num, unit.conversionRate)
              : '0' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */,
          },
        },
      ])
      let obj = {
        target: { value: goodsScrapNum ? accDivMin(old_num, unit.conversionRate) : '0' },
      }
      this.inputNum(obj, props, 'goodsScrapNum')
    },
    dataSourceItem(props, key) {
      let item = this.goodsTable.dataSource[props.index]
      let val = item[key]
      if (key == 'unitList') {
        return JSON.parse(val)
      } else {
        return val
      }
    },
    // 点击新增商品按钮，弹出多选组件
    selectMulti() {
      if (!this.buildForm.warehouseOutId) {
        this.$antdMessage.warning('请先选择出库仓库')
        return
      }
      if (!this.buildForm.warehouseInId) {
        this.$antdMessage.warning('请先选择入库仓库')
        return
      }
      let par = {
        list: `/wms/wmsWarehouse/getOutGoodsListForAllot?warehouseId=${this.getSelWarehouseGoodsId}`,
        visible: true, //弹窗开启
        title: '商品', //标题名称
        multi: 'checkbox', //是否多选
        columns: this.selectColumns, //表格配置
        value: this.selectdGoodsIds || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'goodsId', //需要拿到数据的key，如：id，userId等
        text: this.selectedGoodsNames || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.goodsTableSelectMulti.getInit(par)
    },
    // 多选-选择商品回调
    async getSelectMultiValue(id, text, item) {
      console.log(id, text, item)
      var { values } = this.$refs.goodsTable.getValuesSync({ validate: false })
      let newArr = []
      let tips = ''
      /* 当前选择商品是否已存在列表中↓ */
      values.forEach((val) => {
        item.forEach((son) => {
          if (val.goodsId == son.goodsId) {
            tips += `${son.goodsName},`
            son.delete = true
          }
        })
      })
      /* 若已存在列表中，则删除商品，不参与新增↓ */
      for (let i = 0; i < item.length; i++) {
        const good = item[i]
        if (!good.delete) {
          const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: good.goodsId })
          newArr.push({
            unitList: JSON.stringify(unitRes.result),
            rateQ: 1,
            rateS: 1,
            rateQOld: 1,
            rateSOld: 1,
            selectUnitQ: unitRes.result[unitRes.result.length - 1].id,
            selectUnitS: unitRes.result[unitRes.result.length - 1].id,

            goodsCode: good.goodsCode,
            goodsName: good.goodsName,
            spec: good.spec || '-',
            kcGoodsQualifiedNum: good.kcGoodsQualifiedNum,
            kcGoodsScrapNum: good.kcGoodsScrapNum,
            goodsId: good.goodsId,
          })
        }
      }
      if (newArr.length > 0) {
        this.goodsTable.dataSource = values.concat(newArr)
        this.selectedGoodsNames = ''
        this.selectdGoodsIds = ''
        this.selectMultiIndex += 1
        if (tips != '') {
          this.$antdMessage.warning(`物品：${tips}已存在，请直接修改数据`)
        }
      } else {
        this.selectedGoodsNames = ''
        this.selectdGoodsIds = ''
        this.selectMultiIndex += 1
        if (tips != '') {
          this.$antdMessage.warning(`物品：${tips}已存在，请直接修改数据`)
        }
      }
    },
    // 点击选择商品下拉框，弹出选择组件
    showSelect(p) {
      this.goodsProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.goodsProps.rowId] })
        .values[0]
      let par = {
        list: `/wms/wmsWarehouse/getOutGoodsListForAllot?warehouseId=${this.getSelWarehouseGoodsId}`,
        visible: true, //弹窗开启
        title: '物品', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.goodsId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'goodsId', //需要拿到数据的key，如：id，userId等
        text: tableValue.goodsName || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.goodsTableSelect.getInit(par)
    },
    // 项目选择框回显值
    projectNameText(p) {
      var item = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      console.log('itemssssss:', item)
      // return `${item.projectCode ? item.projectCode : ''}${item.projectName ? item.projectName : ''}`
      return `${item.goodsCode ? item.goodsCode : ''}`
    },
    // 重置
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.goodsTableSelect.searchReset()
    },
    // 筛选
    searchGoods() {
      console.log(this.filterForm, '---this.filterForm')
      this.$refs.goodsTableSelect.searchQuery(this.filterForm)
    },
    // 选择商品回调
    // 选择项目回调
    getSelectValue(id, text, item, p) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      console.log(id, text, item, p, '---getSelectValue')
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: p.rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              goodsCode: '',
              goodsName: '',
              spec: '',
              kcGoodsQualifiedNum: '',
              kcGoodsScrapNum: '',
              goodsId: '',
            },
          },
        ])
        return
      }
      let tempGoodsCode = ''
      let tempGoodsName = ''
      let tempspec = ''
      let tempkcGoodsQualifiedNum = ''
      let tempkcGoodsScrapNum = ''
      let tempGoodsId = ''
      for (let items of this.stockGoodList) {
        if (items.goodsId == id) {
          tempGoodsCode = items.goodsCode
          tempGoodsName = items.goodsName
          tempspec = items.spec || '-'
          tempkcGoodsQualifiedNum = items.kcGoodsQualifiedNum
          tempkcGoodsScrapNum = items.kcGoodsScrapNum
          tempGoodsId = items.goodsId
        }
      }
      console.log(this.goodsProps, '---goodsProps')
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.goodsProps.rowId, // 行的id
          values: {
            goodsCode: tempGoodsCode,
            goodsName: tempGoodsName,
            spec: tempspec,
            kcGoodsQualifiedNum: tempkcGoodsQualifiedNum,
            kcGoodsScrapNum: tempkcGoodsScrapNum,
            goodsId: tempGoodsId,
          },
        },
      ])
      let { err, values } = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.goodsProps.rowId] })
      console.log(values, '---getValuesSync')
      // this.$refs.goodsTable.setValues([
      //   {
      //     rowKey: this.goodsProps.rowId, // 行的id
      //     values: {
      //       // 在这里 values 中的 goodsId 是你 columns 中配置的 key
      //       itemId: item[0].id,
      //       projectName: item[0].projectName,
      //       projectCode: `${item[0].projectCode}-${item[0].projectName}`,
      //       maintainStandard: item[0].maintainStandard,
      //     },
      //   },
      // ])
      this.setGoodsInfo(id, p)
      console.log(id, text, item, this.goodsProps.rowId, '列表选择的数据')
    },
    // 根据选择的项目带出其他商品信息并填充
    setGoodsInfo(value, p) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      var newArr = []
      tableValue.forEach((v) => {
        newArr.push(v.goodsId)
      })
      var newArrLen = [...new Set(newArr)].length
      var oldArrLen = tableValue.length
      if (newArrLen < oldArrLen) {
        console.log(newArrLen, oldArrLen, 'newArrLen---oldArrLen')
        this.$refs.goodsTable.removeRows(this.goodsProps.rowId)
        this.$antdMessage.warning('该物品已存在')
        return
      }
      this.$refs.goodsTable.getValuesSync({ validate: true })
    },
    //
    goodChang(value, props) {
      console.log(value, props, 'goodChang---props')
      let tempGoodsName = ''
      let tempspec = ''
      let tempkcGoodsQualifiedNum = ''
      let tempkcGoodsScrapNum = ''
      let tempGoodsId = ''
      for (let item of this.stockGoodList) {
        if (item.goodsCode == value) {
          console.log(item, '------item')
          tempGoodsName = item.goodsName
          tempspec = item.spec || '-'
          tempkcGoodsQualifiedNum = item.kcGoodsQualifiedNum
          tempkcGoodsScrapNum = item.kcGoodsScrapNum
          tempGoodsId = item.goodsId
        }
      }
      console.log(tempGoodsName, tempspec, '---tempspec')
      this.$refs.goodsTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            goodsCode: value,
            goodsName: tempGoodsName,
            spec: tempspec,
            kcGoodsQualifiedNum: tempkcGoodsQualifiedNum,
            kcGoodsScrapNum: tempkcGoodsScrapNum,
            goodsId: tempGoodsId,
          },
        },
      ])
      let { err, values } = this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
      console.log(values, '---getValuesSync')
    },
    checkUnit(props) {
      let currentValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      console.log(currentValue, 'checkUnit---currentValue')
      if (currentValue.assistUnit) {
        return currentValue.assistUnit
      }
      return ''
    },
    tableAddRow() {
      if (!this.buildForm.warehouseOutId) {
        let { values } = this.$refs.goodsTable.getValuesSync({ validate: true })
        this.$refs.goodsTable.removeRows(values[0].id)
        this.$antdMessage.warning('请先选择出库仓库')
      }
      if (!this.buildForm.warehouseInId) {
        let { values } = this.$refs.goodsTable.getValuesSync({ validate: true })
        this.$refs.goodsTable.removeRows(values[0].id)
        this.$antdMessage.warning('请先选择入库仓库')
      }
    },
    getInStockList() {
      stockAllocQueryWarehouse({ status: 'effective', pageNo: 1, pageSize: 9999 }).then((res) => {
        if (res.success) {
          this.stockLIst = res.result.records
          console.log(this.stockLIst, '---this.stockLIst')
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    // 调出仓库
    stockOutChange(value) {
      console.log(value, 'stockChange---value')
      // console.log(this.$refs.goodsTable, '---this.$refs.goodsTable')
      let { values } = this.$refs.goodsTable.getValuesSync({ validate: false })
      console.log(values, 'stockChange---values')
      let ids = []
      for (let item of values) {
        ids.push(item.id)
      }
      if (!value) {
        this.$refs.goodsTable.removeRows(ids)
      }
      console.log(ids, 'stockChange---ids')
      this.$refs.goodsTable.removeRows(ids)
      this.stockGoodList = []
      let obj = {
        warehouseId: value,
      }
      this.getSelWarehouseGoodsId = value
      this.getSelWarehouseGoodsObj = {
        warehouseId: value,
      }
      // console.log(obj, '---obj')
      queryGoodApi(obj).then((res) => {
        if (res.success) {
          this.stockGoodList = res.result || []
          console.log(this.stockGoodList, '---this.stockGoodList')
          this.validateStockOutIn(value)
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    // 调入仓库
    stockInChange(value) {
      console.log(value, 'stockChange---value')
      this.validateStockOutIn(value)
    },
    operaChange() {
      this.$forceUpdate()
    },
    validateStockOutIn(value) {
      if (!value) {
        return
      }
      console.log(this.buildForm, '---this.buildForm')
      if (this.buildForm.warehouseOutId === this.buildForm.warehouseInId) {
        this.$antdMessage.warning('操作失败，调出仓库与调入仓库应不同')
        this.buildForm.warehouseInId = ''
      }
    },
    // 调拨明细记录方式
    stockTypeChange(value) {
      console.log(this.buildForm, 'stockTypeChange---value')
    },

    genEntityCode() {
      API.genEntityCode({ entityCode: 'WMS_WAREHOUSE_OPERATE' }).then((res) => {
        if (res.code == 200) {
          this.buildForm.orderNumber = res.result
          this.$refs['ruleFormTwo'].validateField(['orderNumber'])
        } else {
          this.buildForm.orderNumber = ''
          this.$refs['ruleFormTwo'].validateField(['orderNumber'])
          this.$antdMessage.error(res.message)
        }
      })
    },
    checkInputValue(value) {
      validateDuplicateValue('wms_warehouse_operate', 'order_number', value, '', (res) => {
        if (res) {
          this.buildForm.orderNumber = ''
          this.$antdMessage.warning(res)
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    inputNum(e, props, inputKey) {
      let newNum = clearNoNum(e.target.value)
      // let { kcGoodsQualifiedNum, kcGoodsScrapNum } = props.getValue()
      let { kcGoodsQualifiedNum, kcGoodsScrapNum, rateQ, rateS } = props.getValue()
      console.log(newNum, kcGoodsQualifiedNum, kcGoodsScrapNum, '---getValue')
      if (inputKey == 'goodsQualifiedNum') {
        if (accMul(newNum, rateQ) > kcGoodsQualifiedNum) {
          this.$antdMessage.warning('操作失败，调拨数量不应大于账面库存。')
          this.$refs.goodsTable.setValues([
            {
              rowKey: props.rowId, // 行的id
              values: {
                // 在这里 values 中的 amount 是你 columns 中配置的 key
                [inputKey]: '',
              },
            },
          ])
          let { err, values } = this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
          return
        }
      } else {
        if (accMul(newNum, rateS) > kcGoodsScrapNum) {
          this.$antdMessage.warning('操作失败，调拨数量不应大于账面库存。')
          this.$refs.goodsTable.setValues([
            {
              rowKey: props.rowId, // 行的id
              values: {
                // 在这里 values 中的 amount 是你 columns 中配置的 key
                [inputKey]: '',
              },
            },
          ])
          let { err, values } = this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
          return
        }
      }
      // if(e.target.value > )
      // checkGoodsExceedApi
      let { values } = this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
      console.log(values, '-------getValuesSync')
      this.$refs.goodsTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            [inputKey]: clearNoNum(e.target.value),
          },
        },
      ])
    },
    handleDeleteGood(props) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.$refs.goodsTable.removeRows(props.rowId)
    },
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.buildForm.dingFileInfo = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        this.processDataVo = e
        console.log(e, this.processDataVo, 'processDataVo')
        // 获取到数据后写表单提交的方法
        // this.saveForm()
        this.handleSubmit()
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },

    handleSubmit() {
      let that = this
      that.$refs.ruleFormTwo.validate((valid) => {
        console.log(valid, '---')

        if (valid) {
          let { error, values } = that.$refs.goodsTable.getValuesSync({
            validate: true,
          })
          console.log(error, values)
          if (values.length == 0) {
            that.$antdMessage.warning('请添加调拨明细')
            return
          } else {
            if (error == 0) {
              let stockAllotGoodDetailList = []
              for (let i = 0; i < values.length; i++) {
                let obj = {}
                let item = values[i]
                console.log('校验通过', item)
                let goodsNum = accAdd(Number(item.goodsQualifiedNum), Number(item.goodsScrapNum))
                if (goodsNum == 0) {
                  this.$antdMessage.warning(`每个物品调拨总数应大于零`)
                  return
                } else if (item.goodsQualifiedNum == '') {
                  item.goodsQualifiedNum = '0'
                } else if (item.goodsScrapNum == '') {
                  item.goodsScrapNum = '0'
                }
                obj.goodsId = item.goodsId
                obj.goodsNum = goodsNum
                obj.qualifiedNum = accMul(item.goodsQualifiedNum, item.rateQ)
                obj.scrapNum = accMul(item.goodsScrapNum, item.rateS)
                stockAllotGoodDetailList.push(obj)
              }
              console.log(this.buildForm, '---...this.buildForm,')
              if (!this.buildForm.operateTime) {
                this.$antdMessage.warning(`调拨时间不能为空`)
                return
              }
              let params = {
                attachment: this.buildForm.dingFileInfo,
                inWarehouseId: this.buildForm.warehouseInId,
                outWarehouseId: this.buildForm.warehouseOutId,
                type: this.buildForm.type,
                allotOrder: this.buildForm.orderNumber,
                applyNo: this.buildForm.orderNumber,
                // createTime: moment(this.buildForm.operateTime).format('YYYY-MM-DD hh:mm:ss'),
                createTime: this.buildForm.operateTime,
                reason: this.buildForm.remark,
                stockAllotGoodDetailList,
                processDataVo: this.processDataVo,
                allotTime: this.buildForm.operateTime,
              }
              // params.operateTime = moment(params.operateTime).format('YYYY-MM-DD hh:mm:ss')
              console.log('当前所有的参数是：', params)
              this.formatParams = { ...params }
              this.submitLoading = true
              this.requsetFace()
            }
          }
        } else {
          return false
        }
      })
    },
    requsetFace() {
      stockAllocationAddApi(this.formatParams).then((res) => {
        if (res.success) {
          this.$antdMessage.success(res.result)
          this.$emit('refresh')
          this.goBack()
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.submitLoading = false
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 188px);
  overflow-y: scroll;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -50px;
  font-size: 14px;
}
.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}
.detail-item {
  width: 30%;
}
.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}
.cards-box {
  height: calc(100vh - 188px);
  overflow-y: scroll;
}
</style>
